<template>
  <div class="userInfo">
    <Header :getGoods="getGoods"  />

    <div class="userInfo-main">
      <div class="userInfo-main-left">
        <div class="userInfo-chose">
          <el-row class="tac">
            <el-col :span="12">
              <el-menu
                class="el-menu-vertical-demo"
                @open="handleOpen"
                @close="handleClose"s
              >
                <el-sub-menu index="1">
                  <template #title>
                    <span>我的订单</span>
                  </template>
                  <el-menu-item index="1-1" @click="updateContent(1)">待付款</el-menu-item>
                  <el-menu-item index="1-2" @click="updateContent(2)">待收货</el-menu-item>
                  <el-menu-item index="1-3" @click="updateContent(3)">已完成</el-menu-item>
                </el-sub-menu>
                <el-menu-item index="2" @click="updateContent(4)">
                  <span>我发布的</span>
                </el-menu-item>
                <el-menu-item index="3" @click="updateContent(5)">
                  <span>退款订单</span>
                </el-menu-item>
                <el-sub-menu index="4">
                  <template #title>
                    <span>账户安全</span>
                  </template>
                  <el-menu-item index="4-1" @click="updateContent(11)">设置密保</el-menu-item>
                  <el-menu-item index="4-2" @click="updateContent(12)">修改密码</el-menu-item>
                </el-sub-menu>
              </el-menu>
            </el-col>
          </el-row>
        </div>
      </div>
      <div class="userInfo-main-right">
        <div class="userInfo-main-right-top">
          <div class="userInfo-main-right-top-left">
            <img :src="userData.avatarPath" alt="Avatar" class="user-avatar" />
            <div class="showUserInfo">
              <div>{{ userData.username }}</div>
              <div>地址: {{ userData.address }}</div>
              <div>账户年龄: {{ userData.accountAge }}年</div>
            </div>
            <div class="showUserInfo-button">
              <button class="changeInfo" @click=" showChangeInfo">修改信息</button>
              <button class="logOut" @click="logOut">退出登录</button>
            </div>
          </div>
          <div class="userInfo-main-right-top-right">
            <div class="userinfo-banner">
              <img src="/public/img/banner.png" class="banner"/>
            </div>
            <div class="five">
              <div class="userInfo-sell" @click="updateContent(7)">我卖出的</div>
              <div class="userInfo-buy" @click="updateContent(8)">我买入的</div>
              <div class="userInfo-follow" @click="updateContent(6)">我的关注</div>
              <div class="userInfo-collect" @click="updateContent(9)">我的收藏</div>
              <div class="userInfo-history" @click="updateContent(10)">浏览历史</div>
            </div>
          </div>
        </div>
        <div class="userInfo-main-right-bot">
          <div v-if="selectedContent === 1">
                <!--待付款 -->
            <div class="pendingPayment">
              <div v-if="items.length > 0">
              <div v-for="item in items" :key="item.id" class="posted-item" @click="gotoGoodsDetail(item.id)">
                <img :src="item.imgPath" alt="Item Image" class="posted-item-image"/>
                <div class="item-details"  >
                  <h3>{{ item.name }}</h3>
                  <p>{{ item.state }}</p>
                  <p>价格: {{ item.price }}</p>
                  <button class="userInfoButton" @click.stop="pay(item.id)">付款</button>
                </div>
              </div>
            </div>
            <div v-else>
              <p>没有待付款的商品</p>
            </div>
            </div>
          </div>
          <div v-if="selectedContent === 2">
              <!--待收货 -->
                <div class="awaitingReceipt">
                    <div v-if="items.length > 0">
                      <div v-for="item in items" :key="item.id" class="posted-item" @click="gotoGoodsDetail(item.id)">
                        <img :src="item.imgPath" alt="Item Image" class="posted-item-image"/>
                        <div class="item-details"  >
                          <h3>{{ item.name }}</h3>
                          <p>{{ item.state }}</p>
                          <p>价格: {{ item.price }}</p>
                          <button class="userInfoButton" @click.stop="confirmReceipt(item.id)">确认收货</button>
                        </div>
                      </div>
                    </div>
                    <div v-else>
                      <p>没有待收货的商品</p>
                    </div>
                </div>
          </div>
          <div v-if="selectedContent === 3">
                <!--已完成 -->
            <div class="completed">
              <div v-if="items.length > 0">
                      <div v-for="item in items" :key="item.id" class="posted-item" @click="gotoGoodsDetail(item.id)">
                        <img :src="item.imgPath" alt="Item Image" class="posted-item-image"/>
                        <div class="item-details"  >
                          <h3>{{ item.name }}</h3>
                          <p>{{ item.state }}</p>
                          <p>价格: {{ item.price }}</p>
                          <button class="userInfoButton">申请退款</button>
                        </div>
                      </div>
                    </div>
                    <div v-else>
                      <p>没有已完成的订单</p>
                    </div>
              </div>
          </div>
          <div v-if="selectedContent === 4">
            <!-- 我发布的 -->
            <div v-if="items.length > 0">
              <div v-for="item in items" :key="item.id" class="posted-item" @click="gotoGoodsDetail(item.id)">
                <img :src="item.imgPath" alt="Item Image" class="posted-item-image"/>
                <div class="item-details"  >
                  <h3>{{ item.name }}</h3>
                  <p>{{ item.state }}</p>
                  <p>价格: {{ item.price }}</p>
                </div>
              </div>
            </div>
            <div v-else>
              <p>没有发布的商品</p>
            </div>
          </div>
          <div v-if="selectedContent === 5">
                <!-- 退款订单 -->
            <div class="refundOrder">5</div>
          </div>
          <div v-if="selectedContent === 6">
            <!-- 我的关注 -->
            <div v-if="myConcernItem.length > 0">
              <div v-for="item in myConcernItem" :key="item.id" class="posted-item">
                <img :src="item.avatarPath" alt="Item Image" class="posted-item-image"/>
                <div class="item-details"  >
                  <h3>{{ item.username }}</h3>
                  <p>{{ item.address }}</p>
                  <p>账户年龄:{{ item.accountAge }}</p>
                </div>
              </div>
            </div>
            <div v-else>
              <p>没有关注的用户</p>
            </div>
          </div>
          <div v-if="selectedContent === 7">
            <!-- 我卖出的 -->
            <div v-if="items.length > 0">
              <div v-for="item in items" :key="item.id" class="posted-item" @click="gotoGoodsDetail(item.id)">
                <img :src="item.imgPath" alt="Item Image" class="posted-item-image"/>
                <div class="item-details"  >
                  <h3>{{ item.name }}</h3>
                  <p>{{ item.state }}</p>
                  <p>价格: {{ item.price }}</p>
                </div>
              </div>
            </div>
            <div v-else>
              <p>没有卖出的商品</p>
            </div>
          </div>
          <div v-if="selectedContent === 8">
                <!-- 我买入的 -->
            <div class="iBoughtIt">
              <div v-if="items.length > 0">
                      <div v-for="item in items" :key="item.id" class="posted-item" @click="gotoGoodsDetail(item.id)">
                        <img :src="item.imgPath" alt="Item Image" class="posted-item-image"/>
                        <div class="item-details"  >
                          <h3>{{ item.name }}</h3>
                          <p>{{ item.state }}</p>
                          <p>价格: {{ item.price }}</p>
                          <button class="userInfoButton">申请退款</button>
                        </div>
                      </div>
                    </div>
                    <div v-else>
                      <p>还没买到如何东西哦~</p>
                    </div>
            </div>
          </div>
          <div v-if="selectedContent === 9">
            <!-- 我的收藏 -->
            <div v-if="items.length > 0">
              <div v-for="item in items" :key="item.id" class="posted-item" @click="gotoGoodsDetail(item.id)">
                <img :src="item.imgPath" alt="Item Image" class="posted-item-image"/>
                <div class="item-details"  >
                  <h3>{{ item.name }}</h3>
                  <p>{{ item.state }}</p>
                  <p>价格: {{ item.price }}</p>
                </div>
              </div>
            </div>
            <div v-else>
              <p>没有收藏的商品</p>
            </div>
          </div>
          <div v-if="selectedContent === 10">
                <!-- 浏览历史 -->
            <div class="browseHistory">
              <div v-if="items.length > 0">
              <div v-for="item in items" :key="item.id" class="posted-item" @click="gotoGoodsDetail(item.id)">
                <img :src="item.imgPath" alt="Item Image" class="posted-item-image"/>
                <div class="item-details"  >
                  <h3>{{ item.name }}</h3>
                  <p>{{ item.state }}</p>
                  <p>价格: {{ item.price }}</p>
                </div>
              </div>
            </div>
            <div v-else>
              <p>没有浏览过的商品,快去看看吧</p>
            </div>
            </div>
          </div> 
          </div>
        </div>
    </div>
      <div v-if="showContent" class="changeUserInfo-box">
          <div class="changeUserInfo-box-close">
            <el-icon class="changeUserInfo-close-button" @click="showContent = false"><Close /></el-icon>
          </div>
          <div class="changeUserInfo-box-showInfo">
            <p class="avatar-text">头像</p>
              <div class="upload-section" @click="triggerFileInput" :style="{ backgroundImage: filePreviewUrl ? `url(${filePreviewUrl})` : '' }">
                <el-icon v-if="!filePreviewUrl">
                  <Plus />
                </el-icon>
                <input
                  type="file"
                  ref="fileInput"
                  @change="handleFileChange"
                  style="display: none;"
                />
              </div>
              <div class="usernameChange"><p>用户名</p><input type="text" v-model="newUsername"></div>
              <div class="areaChange">
                <p class="areaChange-text">修改地址</p>
                <div class="areaChange-select">
                  <select v-model="selectedProvince" @change="onProvinceChange" class="province">
                    <option value="">请选择省</option>
                    <option v-for="province in areaData.provinces" :key="province.code" :value="province.code">
                      {{ province.name }}
                    </option>
                  </select>
                  <select v-model="selectedCity" @change="onCityChange" :disabled="cities.length === 0" class="city">
                    <option value="">请选择市</option>
                    <option v-for="city in cities" :key="city.code" :value="city.code">
                      {{ city.name }}
                    </option>
                  </select>
                  <select v-model="selectedDistrict" :disabled="districts.length === 0" class="district">
                    <option value="">请选择区/县</option>
                    <option v-for="district in districts" :key="district.code" :value="district.code">
                      {{ district.name }}
                    </option>
                  </select>
                </div>
              </div>
              <div class="areaDetail">
                <textarea class="areaDetail-textarea" v-model="detailedAddress" placeholder="详细地址..."></textarea>
              </div>
          </div>
          <div class="changeUserInfo-box-confirmChange">
            <button class="confirmChange-button" @click="confirmChange">确认修改</button>
          </div>
        </div>
        <div v-if="showSetPasswordSecurity" class="setSecurity-dialog-overlay">
      <div class="setSecurity-dialog">
        <div class="setSecurity-dialog-top">
          <el-icon class="setSecurity-close-button" @click="closeDialog"><Close /></el-icon>
        </div>
        <div class="setSecurity-dialog-min">
          
          <!-- 密码验证部分 -->
          <div v-if="!passwordEntered">
            <input type="password" v-model="password" placeholder="请输入密码"/>
            <button class="verifyPassword-button" @click="verifyPassword">确认</button>
            <p v-if="passwordError" style="color: red;">密码错误，请重试</p>
          </div>

          <!-- 已设置密保问题，并且未进入修改密码流程 -->
          <div v-else-if="securityQuestionsSet.length > 0 && !canChangePassword">
            <h3>请回答以下密保问题：</h3>
            <div v-if="randomQuestion" class="security-question">
              <p>{{ randomQuestion.question }}</p>
              <input type="text" v-model="userAnswer" placeholder="请输入您的答案" />
              <button @click="verifySecurityAnswer">验证答案</button>
              <p v-if="answerError" style="color: red;">答案错误，请重试</p>
              <p v-if="answerCorrect" style="color: green;">答案正确</p>
            </div>
          </div>

          <!-- 答案正确后显示修改密码部分 -->
          <div v-else-if="canChangePassword">
            <h3>修改密码</h3>
            <div class="change-password">
              <input type="password" v-model="newPassword" placeholder="请输入新密码" />
              <input type="password" v-model="confirmPassword" placeholder="请确认新密码" />
              <button @click="changePassword">确认修改</button>
              <p v-if="passwordChangeError" style="color: red;">{{ passwordChangeError }}</p>
              <p v-if="passwordChangeSuccess" style="color: green;">密码修改成功</p>
            </div>
          </div>

          <!-- 未设置密保问题，显示设置密保问题的表单 -->
          <div v-else>
            <h3>请设置您的密保问题</h3>
            <div class="security-question">
              <input type="text" v-model="question1" placeholder="问题1:请输入您的第一个密保问题" />
              <input type="text" v-model="answer1" placeholder="答案1:请输入您的第一个问题的答案" />
            </div>
            <div class="security-question">
              <input type="text" v-model="question2" placeholder="问题2:请输入您的第二个密保问题" />
              <input type="text" v-model="answer2" placeholder="答案2:请输入您的第二个问题的答案" />
            </div>
            <div class="security-question">
              <input type="text" v-model="question3" placeholder="问题3:请输入您的第三个密保问题" />
              <input type="text" v-model="answer3" placeholder="答案3:请输入您的第三个问题的答案" />
            </div>
          </div>

        </div>
        <!-- 设置密保问题按钮，仅在需要设置密保问题时显示 -->
        <div class="setSecurity-dialog-bot" v-if="passwordEntered && securityQuestionsSet.length === 0">
          <button class="confirmSet" @click="submitSecurityQuestions">设置密保</button>
        </div>
      </div>
    </div>
    </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import Header from './Header.vue';
import { useRouter } from 'vue-router';
import '../css/userInfo.css'

// 数据结构
interface District {
  code: string;
  name: string;
}

interface City {
  code: string;
  name: string;
  districts: District[];
}

interface Province {
  code: string;
  name: string;
  cities: City[];
}

interface AreaResponse {
  provinces: Province[];
}

interface Item {
  id: number;
  imgPath: string;
  name: string;
  state: string;
  price: number;
}
 interface MyConcernItem{
  id:number;
  username:string
  avatarPath:string;
  address:string;
  accountAge:number;
 }
 interface SecurityQuestion {
  id: number;
  userId: number;
  question: string;
  answer: string;
}

// 数据
const areaData = ref<AreaResponse>({ provinces: [] });
const items = ref<Item[]>([]);
const myConcernItem = ref<MyConcernItem[]>([]);
const selectedProvince = ref<string>('');
const cities = ref<City[]>([]);
const selectedCity = ref<string>('');
const districts = ref<District[]>([]);
const selectedDistrict = ref<string>('');
const fileInput = ref<HTMLInputElement | null>(null);
const uploadedFile = ref<File | null>(null); // 用于存储上传的文件
const filePreviewUrl = ref<string | null>(null); // 用于存储图片预览URL
const detailedAddress = ref<string>(''); // 用于存储详细地址
const router = useRouter();
const loginId = Number(localStorage.getItem('userId'));
const token = localStorage.getItem('token');
const selectedContent = ref();
const showContent = ref(false);
const userData = ref({
  id: 0,
  username: '',
  address: '',
  avatarPath: '',
  accountAge: 0,
});
const newUsername = ref(userData.value.username);

const password = ref('');
const passwordEntered = ref(false);
const passwordError = ref(false);
const answerError = ref(false);    // 用于显示答案错误提示

// 密保问题和答案的模型
const question1 = ref('');
const answer1 = ref('');
const question2 = ref('');
const answer2 = ref('');
const question3 = ref('');
const answer3 = ref('');
const showSetPasswordSecurity = ref(false);
const userAnswer = ref('');
const answerCorrect = ref(false);
const canChangePassword = ref(false);
const newPassword = ref('');
const confirmPassword = ref('');
const passwordChangeError = ref('');
const passwordChangeSuccess = ref(false);
const securityQuestionsSet = ref<SecurityQuestion[]>([]);
const randomQuestion = ref<SecurityQuestion | null>(null);
const isSetPasswordSecurity = ref(false)

const getUserLink = "http://localhost:8080/user/getUser";
const getAreaLink = "http://localhost:8080/user/areas";
const updateUserLink = "http://localhost:8080/user/updateUser";
const iPostedLink = "http://localhost:8080/goods/getIPosted";
const iSoldLink = "http://localhost:8080/goods/iSold";
const myConcernLink = "http://localhost:8080/follow/myConcern";
const myCollectionLink = "http://localhost:8080/collect/myCollection";
const getObligationLink = "http://localhost:8080/goods/getObligation";
const getPendingReceiptLink = "http://localhost:8080/goods/getPendingReceipt";
const confirmReceiptLink = "http://localhost:8080/order/confirmReceipt";
const getCompletedLink = "http://localhost:8080/goods/getCompleted";
const verifyPasswordLink = "http://localhost:8080/user/verifyPassword";
const submitSecurityQuestionsLink = "http://localhost:8080/user/setSecurityQuestions";
const getSecurityQuestionsLink = "http://localhost:8080/user/getSecurityQuestions";
const changePasswordLink = "http://localhost:8080/user/changePassword";
const getHistoryLink = "http://localhost:8080/goods/getHistory";




const handleFileChange = () => {
  if (fileInput.value && fileInput.value.files) {
    const file = fileInput.value.files[0];
    if (file && file.type.startsWith('image/')) { // 检查文件类型
      uploadedFile.value = file;
      const reader = new FileReader();
      reader.onload = (e) => {
        if (e.target?.result) {
          filePreviewUrl.value = e.target.result as string;
        }
      };
      reader.readAsDataURL(file);
    } else {
      alert('请上传图片文件');
    }
  }
};

const triggerFileInput = () => {
  if (fileInput.value) {
    fileInput.value.click();
  }
};

const handleOpen = () => {}
const handleClose = () => {}

const updateContent = (content: Number) => {
  selectedContent.value = content;  
  switch (content) {
    case 1:
    getObligation()
      break;
    case 2:
    getPendingReceipt()
      break;
    case 3:
    getCompleted()
      break;
    case 4:
      iPosted()
      break;
    case 5:
      break;
    case 6:
      myConcern()
      break;
    case 7:
      iSold()
      break;
    case 8:
    getCompleted()
      break;
    case 9:
      myCollection()
      break;
    case 10:
    getHistory()
      break;
    case 11:
    ShowSetPasswordSecurity()
      break;
    case 12:
    ShowChangePassword()
      break;  
  }
}

const getUser = async () => {
  if (!token) {
    router.push({ name: 'Login' });
  } else {
    try {
      const response = await axios.post(getUserLink, loginId, {
        headers: { 
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
      });
      userData.value = response.data.data;
      newUsername.value = userData.value.username; // 同步用户名
    } catch (error) {
      alert('失败: ' + error);
    }
  }
};

const logOut = () => {
  localStorage.removeItem('token');
  localStorage.removeItem('avatarPath');
  localStorage.removeItem('userId')
  router.push({ name: 'Home' });
};

const fetchData = async () => {
  try {
    const response = await axios.get(getAreaLink, {
      headers: { 
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
    });
    areaData.value = response.data;
  } catch (error) {
    console.error('获取数据失败:', error);
    alert('获取数据失败，请稍后再试。');
  }
};

const onProvinceChange = () => {
  const province = areaData.value.provinces.find(p => p.code === selectedProvince.value);
  if (province) {
    cities.value = province.cities;
    selectedCity.value = '';
    districts.value = [];
    selectedDistrict.value = '';
  }
};

const onCityChange = () => {
  const province = areaData.value.provinces.find(p => p.code === selectedProvince.value);
  if (province) {
    const city = province.cities.find(c => c.code === selectedCity.value);
    if (city) {
      districts.value = city.districts;
      selectedDistrict.value = '';
    }
  }
};

const confirmChange = async () => {
  const selectedProvinceName = areaData.value.provinces.find(p => p.code === selectedProvince.value)?.name || '未选择省';
  const selectedCityName = cities.value.find(c => c.code === selectedCity.value)?.name || '未选择市';
  const selectedDistrictName = districts.value.find(d => d.code === selectedDistrict.value)?.name || '未选择区/县';
  const detailedAddressValue = detailedAddress.value || '未填写详细地址';

  try {
    const formData = new FormData();
    
    // 添加用户数据到FormData
    formData.append('id', loginId.toString());
    formData.append('username', newUsername.value); // 使用新的用户名
    formData.append('provinceName', selectedProvinceName);
    formData.append('cityName', selectedCityName);
    formData.append('districtName', selectedDistrictName);
    formData.append('address', detailedAddressValue);
    
    // 添加文件数据到FormData
    if (uploadedFile.value) {
      formData.append('file', uploadedFile.value);
    }
    const response = await axios.post(updateUserLink, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
        'Authorization': `Bearer ${token}`
      },
    });
    const result = response.data;
    const state = result.state;
    const errMessage = result.errMessage;
    
    if (state) {
      if(result.data.avatarPath!=null){
        localStorage.setItem('avatarPath', result.data.avatarPath);
        window.location.reload();
      }else{
        window.location.reload();
      }
    }else{
      alert(errMessage)
    }
  } catch (error: unknown) {
    console.error('获取消息失败: ' + (error as Error).message);
  }
}

const getObligation = async()=>{
  if (!token) {
    router.push({ name: 'Login' })
    return
  }
  try {
    const response = await axios.post(getObligationLink, loginId,{
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
    })
    items.value=response.data.data;
  } catch (error) {
    console.error(error)
  }
}

const getCompleted = async()=>{
  if (!token) {
    router.push({ name: 'Login' })
    return
  }
  try {
    const response = await axios.post(getCompletedLink, loginId,{
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
    })
    items.value=response.data.data;
  } catch (error) {
    console.error(error)
  }
}

const iPosted  =  async() =>{
  if (!token) {
    router.push({ name: 'Login' })
    return
  }
  try {
    const response = await axios.post(iPostedLink, loginId,{
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
    })

    items.value = response.data.data
  } catch (error) {
    console.error(error)
  }
}

const  iSold =  async() =>{
  if (!token) {
    router.push({ name: 'Login' })
    return
  }
  try {
    const response = await axios.post(iSoldLink, loginId,{
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
    })
    items.value=response.data.data
  } catch (error) {
    console.error(error)
  }
}

const  myConcern =  async() =>{
  if (!token) {
    router.push({ name: 'Login' })
    return
  }
  try {
    const response = await axios.post(myConcernLink, loginId,{
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
    })
    myConcernItem.value = response.data.data
  } catch (error) {
    console.error(error)
  }
}

const myCollection = async()=>{
  if (!token) {
    router.push({ name: 'Login' })
    return
  }
  try {
    const response = await axios.post(myCollectionLink, loginId,{
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
    })
    items.value =response.data.data
  } catch (error) {
    console.error(error)
  }
}

const getPendingReceipt = async()=>{
  if (!token) {
    router.push({ name: 'Login' })
    return
  }
  try {
    const response = await axios.post(getPendingReceiptLink, loginId,{
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
    })
    items.value =response.data.data
  } catch (error) {
    console.error(error)
  }
}

const pay =(id:number)=>{
  if (id!=null) { // 确保 goods.value 不为 null
    try {
      // 跳转到购买页面并传递商品ID
      router.push({ name: 'Buy', query: { id: id.toString() } });
    } catch (error) {
      console.error('跳转到购买页面失败:', error);
    }
  } else {
    alert('商品信息未加载完全');
  }
}

// 确认收货
const confirmReceipt = async (id: number) => {
  if (!token) {
    router.push({ name: 'Login' });
    return;
  }
  try {
     await axios.post(confirmReceiptLink, 
      {
        userId:loginId,       // 传递 userId
        goodsId: [id] // 将 id 包装成数组传递
      }, 
      {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
      }
    );
  } catch (error) {
    console.error(error);
  }
}

// 获取浏览记录
const getHistory = async()=>{
  if (!token) {
    router.push({ name: 'Login' })
    return
  }
  try {
    const response = await axios.post(getHistoryLink, loginId,{
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
    })
    items.value = response.data.data
  } catch (error) {
    console.error(error)
  }
}

// 验证用户密码
const verifyPassword = async () => {
  const userDao = {
    id: loginId,
    password: password.value
  };
  try {
    const response = await axios.post(verifyPasswordLink, userDao, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
    });
    const result = response.data;
    const state = result.state;
    if (state) {
      passwordEntered.value = true;
      passwordError.value = false;
      // 获取密保问题
      userHavePds();
    } else {
      passwordError.value = true;
    }
  } catch (error) {
    console.error(error);
    passwordError.value = true;
  }
};

// 关闭对话框并重置所有状态
const closeDialog = () => {
  showSetPasswordSecurity.value = false;
  passwordEntered.value = false;
  password.value = '';
  passwordError.value = false;
  question1.value = '';
  answer1.value = '';
  question2.value = '';
  answer2.value = '';
  question3.value = '';
  answer3.value = '';
  userAnswer.value = '';
  answerError.value = false;
  answerCorrect.value = false;
  canChangePassword.value = false;
  newPassword.value = '';
  confirmPassword.value = '';
  passwordChangeError.value = '';
  passwordChangeSuccess.value = false;
  isSetPasswordSecurity.value=false;
};



// 提交设置密保问题
const submitSecurityQuestions = async () => {
  // 前端验证所有问题和答案不能为空
  if (!question1.value || !answer1.value || !question2.value || !answer2.value || !question3.value || !answer3.value) {
    alert("所有问题和答案都是必填项");
    return;
  }

  const securityQuestions = {
    id: loginId,
    questions: [
      { question: question1.value, answer: answer1.value },
      { question: question2.value, answer: answer2.value },
      { question: question3.value, answer: answer3.value }
    ]
  };
  try {
    const response = await axios.post(submitSecurityQuestionsLink, securityQuestions, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
    });
    if (response.data.state) {
      alert('密保问题设置成功');
      closeDialog();
    } else {
      alert('密保问题设置失败，请重试');
    }
  } catch (error) {
    alert('网络错误，请稍后再试');
    console.error(error);
  }
};

// 获取已设置的密保问题并随机选择一个
const userHavePds = async () => {
  try {
    const response = await axios.post(getSecurityQuestionsLink,  loginId, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
    });
    // 如果点击的是设置密保则跳过输入密保
    if(isSetPasswordSecurity.value){
      response.data.data.length=0;
    }
    if (response.data.state && response.data.data.length > 0) {
      securityQuestionsSet.value = response.data.data as SecurityQuestion[]; 
      // 随机选择一个密保问题
      const randomIndex = Math.floor(Math.random() * securityQuestionsSet.value.length);
      randomQuestion.value = securityQuestionsSet.value[randomIndex];
    } else {
      securityQuestionsSet.value = [];
      randomQuestion.value = null;
    }
    

    
  } catch (error) {
    console.error(error);
    securityQuestionsSet.value = [];
    randomQuestion.value = null;
  }
};

// 验证用户输入的密保答案
const verifySecurityAnswer = () => {
  if (randomQuestion.value && randomQuestion.value.answer.trim().toLowerCase() === userAnswer.value.trim().toLowerCase()) {
    answerCorrect.value = true;
    answerError.value = false;
    canChangePassword.value = true;
  } else {
    answerCorrect.value = false;
    answerError.value = true;
  }
};

// 修改密码
const changePassword = async () => {
  // 前端验证新密码和确认密码
  if (newPassword.value !== confirmPassword.value) {
    passwordChangeError.value = '两次输入的密码不一致';
    passwordChangeSuccess.value = false;
    return;
  }

  if (newPassword.value.length < 6) {
    passwordChangeError.value = '密码长度必须至少为6位';
    passwordChangeSuccess.value = false;
    return;
  }

  const changePasswordData = {
    id: loginId,
    newPassword: newPassword.value
  };

  try {
    const response = await axios.post(changePasswordLink, changePasswordData, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
    });

    if (response.data.state) {
      passwordChangeSuccess.value = true;
      passwordChangeError.value = '';
      alert("修改成功，请重新登录");
      logOut()
    } else {
      passwordChangeError.value = '密码修改失败，请重试';
      passwordChangeSuccess.value = false;
    }
  } catch (error) {
    console.error(error);
    passwordChangeError.value = '网络错误，请稍后再试';
    passwordChangeSuccess.value = false;
  }
};

const ShowSetPasswordSecurity=()=>{
  isSetPasswordSecurity.value =true
  showSetPasswordSecurity.value = true
}
const ShowChangePassword=()=>{
  isSetPasswordSecurity.value =false
  showSetPasswordSecurity.value = true
}
const gotoGoodsDetail=(id:number)=>{
  router.push({ path: `/goods/${id}` })
}

const showChangeInfo=()=>{
  showContent.value =true;
  fetchData();
}

const getGoods = (filterObject: { name: string; platform: string; sortType: string; categoriesId: number }) => {
  
};
onMounted(() => {
  getUser();
});
</script>